package com.jeesite.modules.jdProduct.utils;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.cache.JedisUtils;
import com.jeesite.common.utils.MD5;
import com.jeesite.modules.jdProduct.contact.ApiContact;
import com.jeesite.modules.jdProduct.entity.TokenPojo;
import com.jeesite.modules.pay.totalPay.util.HttpXmlUtils;

public class TokenUtils {
	public static String getToken(){
		/*if(true){
			return "a9bac76b8fa04f1bbe1f5e42dfc734478";
		}*/
		return JedisUtils.get("token");
		/*String accessToken="";
		if(tp!=null){
			accessToken=tp.getAccess_token();
			return accessToken; 
		}
		TokenPojo tokenPojo=new TokenPojo();
		//grant_type=password&app_key="+appKey+"&app_secret="+appSecret+"&state=0&username="+username+"&password="+password
		String params="grant_type=password&app_key="+ApiContact.appKey+"&app_secret="+ApiContact.appSecret+"&state=0&username="+ApiContact.username+"&password="+MD5.md5(ApiContact.password);
		
		//{"access_token":"d1637fb2219645d9aff4da792de74f898","code":"0","expires_in":2592000,"refresh_token":"eca718f0713b4a769a9808871a75ca2a9","time":"1554622464657","token_type":"bearer","uid":"05841424428","user_nick":"gzlh2019"}
		
		String resultToken = HttpXmlUtils.httpsRequest(ApiContact.tokenUrl, params);
		if(StringUtils.isNotBlank(resultToken)){
		JSONObject jo=JSONObject.parseObject(resultToken);
	
		
		String code=jo.getString("code");
		if("0".equals(code)){
		String access_token=jo.getString("access_token");
		int expires_in=jo.getInteger("expires_in");
		String refresh_token=jo.getString("refresh_token");
		String time=jo.getString("time");
		String uid=jo.getString("uid");
		String user_nick=jo.getString("user_nick");
		tokenPojo.setAccess_token(access_token);
		tokenPojo.setExpires_in(expires_in);
		tokenPojo.setRefresh_token(refresh_token);
		tokenPojo.setTime(time);
		tokenPojo.setUid(uid);
		tokenPojo.setUser_nick(user_nick);
		
		JedisUtils.setObject("tokenPojo", tokenPojo, expires_in);
		
		}else if("1004".equals(code)){
			 params="grant_type=refresh_token&app_key="+ApiContact.appKey+"&app_secret="+ApiContact.appSecret+"&state=xxx&username="+ApiContact.username+"&password="+MD5.md5(ApiContact.password);  
			 resultToken = HttpXmlUtils.httpsRequest(ApiContact.refreshTokenUrl, params);
			 
			 String access_token=jo.getString("access_token");
				int expires_in=jo.getInteger("expires_in");
				String refresh_token=jo.getString("refresh_token");
				String time=jo.getString("time");
				String uid=jo.getString("uid");
				String user_nick=jo.getString("user_nick");
				
				tokenPojo.setAccess_token(access_token);
				tokenPojo.setExpires_in(expires_in);
				tokenPojo.setRefresh_token(refresh_token);
				tokenPojo.setTime(time);
				tokenPojo.setUid(uid);
				tokenPojo.setUser_nick(user_nick);
				
				JedisUtils.setObject("tokenPojo", tokenPojo, expires_in);
				
		}
		 
		}
		return tokenPojo.getAccess_token();*/
		
	}
	
}
